﻿using Microsoft.Win32;
using System.Data.OleDb;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml;
using System;

namespace Yonyou.U8.QuickImport
{
    public class TxtToXml : IDataImport
    {
        private bool IsEmpty;

        private Context _Context;

        public bool ArchIsEmpty
        {
            get
            {
                return IsEmpty;
            }
        }

        public event InitialRows InitSetup;

        public event SetValue ValueSet;

        [Obsolete]
        public string[] transform(string type, string filename, string proctype)
        {
            DataSet dataSet = FillDataset(filename, type);
            XslTransform xslTransform = new XslTransform();
            string url = CommonUtil.LoadStyleSheet(type, _Context.Login);
            try
            {
                xslTransform.Load(url);
            }
            catch (XsltCompileException ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
            catch (XmlException ex2)
            {
                MessageBox.Show(ex2.Message);
                return null;
            }
            try
            {
                XsltArgumentList xsltArgumentList = new XsltArgumentList();
                xsltArgumentList.AddParam("proctype", "", proctype);
                DataTable dataTable = dataSet.Tables[0];
                DeleteEmptyRow(dataTable);
                if (dataTable.Rows.Count <= 0 && proctype != "4")
                {
                    IsEmpty = true;
                    return null;
                }
                this.InitSetup(dataTable.Rows.Count, Path.GetFileNameWithoutExtension(filename));
                this.ValueSet(dataTable.Rows.Count / 2);
                string xml = dataSet.GetXml();
                xml = TrimXmlField(xml);
                StringReader textReader = new StringReader(xml);
                XPathDocument input = new XPathDocument(textReader);
                MemoryStream memoryStream = new MemoryStream();
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, null);
                xmlTextWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='utf-8'");
                xslTransform.Transform(input, xsltArgumentList, xmlTextWriter, null);
                string[] result = new string[1] { Encoding.UTF8.GetString(memoryStream.GetBuffer()) };
                this.ValueSet(dataTable.Rows.Count);
                return result;
            }
            catch (XmlException ex3)
            {
                MessageBox.Show("excel向dataset转换出错：" + ex3.Message);
                return null;
            }
        }

        public void logWrite(string logfilename, string[,] strLog, string[] rxmlstr, string id, string proctype)
        {
            string text = "";
            string text2 = "";
            try
            {
                RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Jet\\4.0\\Engines\\Text");
                text = registryKey.GetValue("Format").ToString();
                registryKey.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("无法获取注册表项HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Jet\\4.0\\Engines\\Text\\Format的键值!", "分隔符", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            switch (text)
            {
                case "TabDelimited":
                    text2 = "\t";
                    break;
                case "CSVDelimited":
                    text2 = ",";
                    break;
                default:
                    switch (text.Substring(10, 1))
                    {
                        case "$":
                            text2 = "$";
                            break;
                        case "%":
                            text2 = "%";
                            break;
                        case "@":
                            text2 = "@";
                            break;
                        default:
                            text2 = ",";
                            break;
                    }
                    break;
            }
            string text3 = logfilename + "_inner";
            StreamReader streamReader = new StreamReader(logfilename, Encoding.GetEncoding("gb2312"));
            StreamWriter streamWriter = new StreamWriter(text3, false, Encoding.GetEncoding("gb2312"));
            string text4 = streamReader.ReadLine();
            string text5 = "";
            int num = 0;
            while (text4 != null && num < strLog.Length)
            {
                if (proctype == "3")
                {
                    text4 = text4.Substring(text4.IndexOf(",") + 1);
                }
                text5 = strLog[num, 0] + text2 + text4;
                streamWriter.WriteLine(text5);
                text4 = streamReader.ReadLine();
                num++;
            }
            streamReader.Close();
            streamWriter.Close();
            File.Copy(text3, logfilename, true);
            File.Delete(text3);
        }

        public TxtToXml(Context context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            _Context = context;
            IsEmpty = false;
        }

        private DataSet FillDataset(string filename, string type)
        {
            string directoryName = Path.GetDirectoryName(filename);
            if (string.Compare(directoryName, Context.QIPath + "\\Txt", true) != 0)
            {
                string[] files = Directory.GetFiles(Context.QIPath + "\\Txt", "*.txt");
                string[] array = files;
                foreach (string path in array)
                {
                    File.Delete(path);
                }
                files = Directory.GetFiles(Context.QIPath + "\\Txt", "*.csv");
                string[] array2 = files;
                foreach (string path2 in array2)
                {
                    File.Delete(path2);
                }
                File.Copy(filename, Context.QIPath + "\\Txt\\" + Path.GetFileName(filename), true);
                filename = Context.QIPath + "\\Txt\\" + Path.GetFileName(filename);
            }
            ResetSchemaIni(filename);
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Path.GetDirectoryName(filename) + "; Extended Properties='text;HDR=Yes;FMT=Delimited'";
            OleDbConnection oleDbConnection = new OleDbConnection(connectionString);
            oleDbConnection.Open();
            OleDbCommand selectCommand = new OleDbCommand("SELECT * FROM [" + Path.GetFileName(filename) + "]", oleDbConnection);
            OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter();
            oleDbDataAdapter.SelectCommand = selectCommand;
            DataSet dataSet = new DataSet();
            dataSet.DataSetName = "ufinterface";
            oleDbDataAdapter.Fill(dataSet, type);
            DateTimeToString(dataSet);
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(Path.Combine(Context.U8Path, "ExcelModel\\ChildArch.xml"));
            XmlNode xmlNode = xmlDocument.SelectSingleNode("//arch[@type='" + type + "']");
            if (xmlNode != null)
            {
                XmlNodeList childNodes = xmlNode.ChildNodes;
                foreach (XmlNode item in childNodes)
                {
                    string text = item.Attributes.GetNamedItem("filepath").InnerText;
                    if (text.Trim().Length != 0)
                    {
                        string innerText = item.Attributes.GetNamedItem("type").InnerText;
                        string directoryName2 = Path.GetDirectoryName(text);
                        if (string.Compare(directoryName2, Context.QIPath + "\\Txt", true) != 0)
                        {
                            File.Copy(filename, Context.QIPath + "\\Txt\\" + Path.GetFileName(text), true);
                            text = Context.QIPath + "\\Txt\\" + Path.GetFileName(text);
                        }
                        ResetSchemaIni(text);
                        selectCommand = (oleDbDataAdapter.SelectCommand = new OleDbCommand("select * from " + Path.GetFileName(text), oleDbConnection));
                        oleDbDataAdapter.Fill(dataSet, innerText);
                    }
                }
            }
            oleDbConnection.Close();
            return dataSet;
        }

        private void ResetSchemaIni(string filename)
        {
            string text = Context.QIPath + "\\Txt\\Schema.ini";
            string text2 = text + "_inner";
            StreamReader streamReader = new StreamReader(text);
            streamReader.ReadLine();
            string value = streamReader.ReadToEnd();
            streamReader.Close();
            StreamWriter streamWriter = new StreamWriter(text2);
            streamWriter.WriteLine("[" + Path.GetFileName(filename) + "]");
            streamWriter.Write(value);
            streamWriter.Close();
            File.Copy(text2, text, true);
            File.Delete(text2);
        }

        private void AddSchema(string filename)
        {
        }

        private void DeleteEmptyRow(DataTable table)
        {
            int num = table.Rows.Count - 1;
            while (num >= 0)
            {
                bool flag = false;
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    if (table.Rows[num][i].ToString().Trim() != "")
                    {
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    table.Rows.RemoveAt(num);
                    num--;
                    continue;
                }
                break;
            }
        }

        private void DateTimeToString(DataSet dataset)
        {
            DataTable dataTable = dataset.Tables[0];
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                DataColumn dataColumn = dataTable.Columns[i];
                if (dataColumn.DataType != Type.GetType("System.DateTime"))
                {
                    continue;
                }
                DataColumn dataColumn2 = dataTable.Columns.Add(dataColumn.Caption + "new", Type.GetType("System.String"));
                for (int j = 0; j < dataTable.Rows.Count; j++)
                {
                    string text = dataTable.Rows[j][dataColumn].ToString().Trim();
                    if (text.Length > 8)
                    {
                        dataTable.Rows[j][dataColumn2] = text.Remove(text.Length - 8, 8);
                    }
                }
                dataTable.Columns.Remove(dataColumn);
                dataColumn2.Caption = dataColumn.Caption;
                dataColumn2.ColumnName = dataColumn.ColumnName;
            }
        }

        private string TrimXmlField(string strxml)
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlDocument xmlDocument2 = new XmlDocument();
            try
            {
                xmlDocument.LoadXml(strxml);
                xmlDocument2.LoadXml(strxml);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return strxml;
            }
            xmlDocument2.SelectSingleNode("/ufinterface").RemoveAll();
            XmlNodeList childNodes = xmlDocument.SelectSingleNode("/ufinterface").ChildNodes;
            foreach (XmlNode item in childNodes)
            {
                XmlNodeList childNodes2 = item.ChildNodes;
                XmlNode xmlNode2 = xmlDocument2.CreateNode(item.NodeType, item.Name, item.NamespaceURI);
                foreach (XmlNode item2 in childNodes2)
                {
                    string name = item2.Name.Replace("_x0020_", "");
                    XmlNode xmlNode4 = xmlDocument2.CreateNode(item2.NodeType, name, item2.NamespaceURI);
                    xmlNode4.InnerText = item2.InnerText;
                    xmlNode2.AppendChild(xmlNode4);
                }
                xmlDocument2.SelectSingleNode("/ufinterface").AppendChild(xmlNode2);
            }
            return xmlDocument2.InnerXml;
        }
    }
}